package com.punai.datapush.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.bos.KVBO;
import com.punai.common.enums.ReleaseState;
import com.punai.common.utils.StringUtil;
import com.punai.datapush.domain.EcoReleaseIndicator;
import com.punai.datapush.domain.IndexZBStructItem;
import com.punai.datapush.domain.dto.IndicatorReleaseForm;
import com.punai.datapush.domain.dto.IndicatorSelectProjectForm;
import com.punai.datapush.mapper.EcoReleaseIndicatorMapper;
import com.punai.datapush.mapper.EcoZbStructItemIndexMapper;
import com.punai.datapush.service.IEcoReleaseIndicatorService;
import com.punai.externalccb.bo.EcoZbstructitemBo;
import com.punai.externalccb.domain.EcoCbbidnode;
import com.punai.externalccb.domain.EcoZbstructitem;
import com.punai.externalccb.mapper.EcoCbbidnodeMapper;
import com.punai.externalccb.mapper.EcoZbstructitemMapper;
import com.punai.prodatalibrary.domain.bo.GlobalProInfoBo;
import com.punai.prodatalibrary.mapper.LibProjectMapper;
import org.apache.commons.collections4.ListValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author zxw_
 * @date 2023-05-03
 */
@Service
public class EcoReleaseIndicatorServiceImpl extends ServiceImpl<EcoReleaseIndicatorMapper, EcoReleaseIndicator> implements IEcoReleaseIndicatorService {
    @Autowired
    private EcoReleaseIndicatorMapper ecoReleaseIndicatorMapper;

    @Autowired
    private EcoZbstructitemMapper ecoZbstructitemMapper;

    @Autowired
    private LibProjectMapper libProjectMapper;

    @Autowired
    private EcoZbStructItemIndexMapper itemIndexMapper;

    @Autowired
    private EcoCbbidnodeMapper ecoCbbidnodeMapper;


    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public EcoReleaseIndicator selectEcoReleaseIndicatorById(String id) {
        return ecoReleaseIndicatorMapper.selectEcoReleaseIndicatorById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param ecoReleaseIndicator 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<EcoReleaseIndicator> selectEcoReleaseIndicatorList(EcoReleaseIndicator ecoReleaseIndicator) {
        return ecoReleaseIndicatorMapper.selectEcoReleaseIndicatorList(ecoReleaseIndicator);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param ecoReleaseIndicator 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertEcoReleaseIndicator(EcoReleaseIndicator ecoReleaseIndicator) {
        return ecoReleaseIndicatorMapper.insert(ecoReleaseIndicator);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param ecoReleaseIndicator 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateEcoReleaseIndicator(EcoReleaseIndicator ecoReleaseIndicator) {
        return ecoReleaseIndicatorMapper.updateById(ecoReleaseIndicator);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteEcoReleaseIndicatorByIds(String[] ids) {
        return ecoReleaseIndicatorMapper.deleteEcoReleaseIndicatorByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteEcoReleaseIndicatorById(String id) {
        return ecoReleaseIndicatorMapper.deleteEcoReleaseIndicatorById(id);
    }

    @Override
    public List<GlobalProInfoBo> selectTableData(IndicatorSelectProjectForm form) {
        String stagetype = form.getStagetype();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("stagetype", stagetype);
        List<String> queryMap = ecoZbstructitemMapper.findAllProId(stagetype);
        List<String> proIds = new ArrayList<>();

        if (CollUtil.isEmpty(queryMap)) {
            return new ArrayList<>();
        }

        for (String proId : queryMap) {
            proIds.add(proId);
        }


        Map<String, Object> map = new HashMap<>();
        map.putAll(BeanUtil.beanToMap(form));
        map.put("proIds", proIds);
        List<GlobalProInfoBo> infoBoList = libProjectMapper.findAllByProId(map);
        return infoBoList;
    }

    @Override
    @Transactional
    public boolean saveCheckedIndicator(String proId, String pubid, String stagetype) {
        itemIndexMapper.delete(Wrappers.<IndexZBStructItem>lambdaQuery().eq(IndexZBStructItem::getIndicatorPubId, pubid));
        int total = ecoZbstructitemMapper.insertIndexZbStructItem(proId, pubid, stagetype);
        return total > 0;
    }

    @Override
    @Transactional
    public boolean saveAndPublishCheckedIndicator(String proId, String pubId, String stagetype) {
        itemIndexMapper.delete(Wrappers.<IndexZBStructItem>lambdaQuery().eq(IndexZBStructItem::getIndicatorPubId, pubId));
        ecoZbstructitemMapper.insertIndexZbStructItem(proId, pubId, stagetype);
        EcoReleaseIndicator one = ecoReleaseIndicatorMapper.selectOne(Wrappers.<EcoReleaseIndicator>lambdaQuery().eq(EcoReleaseIndicator::getId, pubId));
        one.setReleaseState(ReleaseState.Y.getType());
        one.setReleaseDate(new Date());
        ecoReleaseIndicatorMapper.updateById(one);
        return true;
    }

    @Override
    public List<KVBO> findZbListGroupBy(String stagetype, String proId) {
        List<KVBO> kvbos = new ArrayList<>();
        EcoZbstructitem ecoZbstructitem = new EcoZbstructitem();
        ecoZbstructitem.setStagetype(stagetype);
        ecoZbstructitem.setProId(proId);
        List<EcoZbstructitem> all = ecoZbstructitemMapper.selectEcoZbstructitemList(ecoZbstructitem);
        Set<String> collect = all.stream().map(v -> v.getStructid() + "_" + v.getStructname() + "_" + (StringUtil.isNullOrEmpty(v.getShowtype()) ? "11" : v.getShowtype())).collect(Collectors.toSet());
        for (String s : collect) {
            KVBO kvbo = new KVBO();
            String[] split = s.split("_");
            kvbo.setKey(split[0]);
            kvbo.setName(split[1]);
            kvbo.setValue(split[2]);
            kvbos.add(kvbo);
        }
        return kvbos;
    }

    @Override
    public List<EcoZbstructitemBo> findZbList(String stagetype, String proId, String zbid) {
        List<EcoZbstructitemBo> res = new ArrayList<>();
        List<EcoCbbidnode> cbBidNodes = ecoCbbidnodeMapper.selectEcoCbbidnodeList(new EcoCbbidnode(){{
            setProId(proId);
            setNodetype(2);
            setStagetype(stagetype);
        }});
        for (EcoCbbidnode cbBidNode : cbBidNodes) {
            List<EcoZbstructitem> all = ecoZbstructitemMapper.selectEcoZbstructitemList(new EcoZbstructitem(){{
                setProId(proId);
                setStagetype(stagetype);
                setZbid(zbid);
                setBidnodeid(cbBidNode.getBidnodeid());
            }});
            if(all.size()==0)continue;
            all.sort(Comparator.comparingInt(EcoZbstructitem::getKeyid));
            ListValuedMap<String, EcoZbstructitemBo> valuedHashMap = new ArrayListValuedHashMap<>();
            for (EcoZbstructitem ecoZbstructitem : all) {
                if (StringUtil.equals(ecoZbstructitem.getZbpid(), zbid)) ecoZbstructitem.setZbpid("0");
                EcoZbstructitemBo bo = new EcoZbstructitemBo();
                BeanUtil.copyProperties(ecoZbstructitem,bo);
                valuedHashMap.put(ecoZbstructitem.getZbpid(), bo);
            }
            List<EcoZbstructitemBo> roots = valuedHashMap.get("0");
            for (EcoZbstructitemBo root : roots) {
                getChildren(root, valuedHashMap);
                res.add(root);
            }
        }
        return res;
    }

    @Override
    public List<IndexZBStructItem> findListZbstructItemIndex(IndicatorReleaseForm form) {
        List<IndexZBStructItem> indexZBStructItemList = itemIndexMapper.selectList(Wrappers.<IndexZBStructItem>lambdaQuery().eq(IndexZBStructItem::getIndicatorPubId, form.getId()));
        return indexZBStructItemList;
    }

    @Override
    public boolean checkShow(IndicatorReleaseForm form) {
        List<IndexZBStructItem> list = itemIndexMapper.selectList(Wrappers.<IndexZBStructItem>lambdaQuery().eq(IndexZBStructItem::getIndicatorPubId, form.getPubId()));
        if (CollUtil.isEmpty(list)) {
            return false;
        }
        return true;
    }

    public void getChildren(EcoZbstructitemBo root, ListValuedMap<String, EcoZbstructitemBo> valuedHashMap) {
        String zbid = root.getZbid();
        List<EcoZbstructitemBo> list = valuedHashMap.get(zbid);
        if (CollUtil.isNotEmpty(list)) {
            for (EcoZbstructitemBo zbstructitem : list) {
                getChildren(zbstructitem, valuedHashMap);
            }
            root.setChildren(list);
        }
    }

}
